package com.aube.multiscreen;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.asha.vrlib.MDVRLibrary;
import com.asha.vrlib.texture.GLTextureView;
import com.aube.R;
import com.aube.control.player.AbstractVideoHelper;
import com.aube.control.player.ISurfaceTextureProvider;
import com.aube.control.player.MajorVRTextureVideoHelper;
import com.aube.control.player.MultiVideoBalanceAdapter;
import com.aube.control.player.VRTextureVideoHelper;
import com.aube.guide.GuideConstants;
import com.aube.model.VideoItem;
import com.aube.views.RingLoading;
import com.aube.views.vote.AnimatorHelper;
import com.huyn.baseframework.model.ChannelDetail;
import com.huyn.baseframework.model.VideoPlayModel;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.UmengUtils;
import com.huyn.baseframework.utils.Utils;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by huyaonan on 16/6/27.
 * VR镜头
 */
public class VRCardView extends CameraCardView {

    protected MDVRLibrary mVRLibrary;

    protected View mToolLayout, mVideoBg;
    protected ImageView mGesture, mGlass, mVr;

    protected GLTextureView mVrView;

    protected AtomicBoolean mSurfaceFilled = new AtomicBoolean(false);

    public VRCardView(Context context) {
        this(context, null);
    }

    public VRCardView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public VRCardView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    protected void inflateView() {
        LayoutInflater.from(context).inflate(R.layout.layout_vr_card, this);
        mRoot = findViewById(R.id.card_layout);
        mTool = findViewById(R.id.card_tools);

        mVideoBg = findViewById(R.id.card_bg);

        mToolLayout = findViewById(R.id.card_tool_layout);
        mGesture = (ImageView) findViewById(R.id.card_gesture);
        mGlass = (ImageView) findViewById(R.id.card_glass);
        mVr = (ImageView) findViewById(R.id.card_vr);

        mZoom = (ImageView) findViewById(R.id.card_zoom);
        mClose = (ImageView) findViewById(R.id.card_close);

        mTitle = (TextView) findViewById(R.id.card_title);
        mDes = (TextView) findViewById(R.id.card_des);

        mLoading = (RingLoading) findViewById(R.id.card_loading);

        mAudioMask = findViewById(R.id.card_audio_mask);
        mVoice = (ImageView) findViewById(R.id.card_voice_toggle);
        mVoice.setTag(R.id.video_voice, false);

        mVrView = (GLTextureView) findViewById(R.id.card_texturevideo);
        /**必须要在此初始化,不然会crash*/
        prepareVrLibrary();

        if(supportVRMotionMode()) {
            mGesture.setVisibility(View.VISIBLE);
            mGlass.setVisibility(View.VISIBLE);
        } else {
            mGesture.setVisibility(View.GONE);
            mGlass.setVisibility(View.GONE);
        }
    }

    public void initEvent() {
        super.initEvent();
        mGesture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchInteractiveMode();
            }
        });
        mGlass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchDisplayMode();
            }
        });
    }

    public void switchViewSize() {
        super.switchViewSize();

        if(mVr != null) {
            if (isNormalSize)
                mVr.setVisibility(View.GONE);
            else
                mVr.setVisibility(VISIBLE);
        }
    }

    public boolean isVr() {
        return true;
    }

    public void hideTitle(boolean showTopTool) {
        mTool.setVisibility(View.VISIBLE);
        mDes.setVisibility(View.VISIBLE);

        mTitle.setVisibility(View.GONE);
        mToolLayout.setVisibility(View.GONE);
        if (showTopTool) {
            mClose.setVisibility(View.VISIBLE);

            mVr.setVisibility(View.GONE);
        } else {
            mClose.setVisibility(View.GONE);

            mVr.setVisibility(View.VISIBLE);
        }
    }

    public void showTitle() {
//        mTool.setVisibility(View.VISIBLE);
        AnimatorHelper.alphaAnim(mTool, 0f, 1f);

        mClose.setVisibility(View.GONE);
        mToolLayout.setVisibility(View.VISIBLE);
        mTitle.setVisibility(View.VISIBLE);
        mDes.setVisibility(View.GONE);

        mVr.setVisibility(View.VISIBLE);

        postDelayed(new Runnable() {
            @Override
            public void run() {
                GuideConstants.showVrGuide((Activity) getContext(), VRCardView.this, supportVRMotionMode(), null);
            }
        }, 500);
    }

    public void hideAll() {
        mTool.setVisibility(View.GONE);

        mClose.setVisibility(View.GONE);
        mToolLayout.setVisibility(View.GONE);
        mTitle.setVisibility(View.GONE);

        mDes.setVisibility(View.GONE);

        mVr.setVisibility(View.GONE);
    }

    public void manageStateInPIP(boolean showDes) {
        mTool.setVisibility(View.VISIBLE);
        mClose.setVisibility(View.VISIBLE);
        mTitle.setVisibility(View.GONE);
        mToolLayout.setVisibility(View.GONE);

        mVr.setVisibility(View.GONE);

        if (showDes) {
            mDes.setVisibility(View.VISIBLE);
        } else {
            mDes.setVisibility(View.GONE);
        }

        manageAudioAndMask(!showDes);
    }

    public void initClick(final int i) {
        setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (iController != null) {
                    int currentIndex = iController.getCurrentIndex();
                    if (currentIndex == i) {
                        iController.showTools();
                    } else {
                        iController.switchView(v);
                        ChannelDetail channelDetail = iController.getChannelDetail();
                        if (iController.isMiddleMode()) {
                            UmengUtils.reportUmengEvent(context, UmengUtils.EVENT_SWITCH_VIDEO_IN_MIDDLE_SCREEN, UmengUtils.appendLabels(channelDetail.videoid, channelDetail.videoTitle, getTitle()));
                        } else {
                            UmengUtils.reportUmengEvent(context, UmengUtils.EVENT_SWITCH_VIDEO_IN_FULL_SCREEN, UmengUtils.appendLabels(channelDetail.videoid, channelDetail.videoTitle, getTitle()));
                        }
                    }
                }
            }
        });

        mClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (iController != null)
                    iController.removeFromMainPic(VRCardView.this, (String) getTag());
            }
        });
    }

    public void managePadding(boolean showBorder) {
        showBorder(showBorder);

        invalidate();
    }

    public AbstractVideoHelper play(final int i, VideoItem item, final long startTime, boolean play, final IVideoController controller) {
        this.mVideo = item.getVideo();
        prepareVrLibrary();
        mVRLibrary.updateAngleXY(getAngleXY(item.leftRightAngle, item.updownAngle));
        mHelper = new VRTextureVideoHelper(context, mVideo, item.enableSound(), new ISurfaceTextureProvider() {
            @Override
            public Surface getSurface() {
                if(mVRLibrary != null)
                    return mVRLibrary.getSurface();
                return null;
            }
        });
        mHelper.setStartTime(startTime);
        mHelper.initPlayState(play);
        mHelper.setPlayCallback(new AbsPlayCallback() {
            @Override
            public void endPlay() {
                hideLoading();

                if(controller != null && i != 0)
                    controller.endPlay(i);
            }

            @Override
            public void updatePlay(long current, long duration) {
                if (lastPosition == current) {
                    showLoading();
                } else {
                    if(mVideoBg.getVisibility() != View.VISIBLE)
                        hideLoading();
                    lastPosition = current;
                }

                if(MultiVideoBalanceAdapter.getInstance().isLowExperience() && controller != null) {
                    controller.updateProgressBySubVideo(current + mHelper.getStartTime());
                }

                if (current > 500) {
                    //显示声音图标
                    if (mVideoPrepared.get())
                        return;
                    //show voice and mask
                    mVideoPrepared.set(true);

                    //show voice icon if needed
                    managePadding(true);

                    if(mVRLibrary != null && mVRLibrary.getSurface() != null)
                        updateSurface(mVRLibrary.getSurface());
                }
            }

//            @Override
//            public void clearLoading() {
//                hideLoading();
//            }

            @Override
            public void syncSuccess() {
                mVideoBg.setVisibility(View.GONE);
            }
        });

        //防止surface为空播放不出来
        if(mVRLibrary != null && mVRLibrary.getSurface() != null)
            updateSurface(mVRLibrary.getSurface());

        showLoading();
        initContent(item, i, controller);
        return mHelper;
    }

    public void initContent(VideoItem item, int i, IVideoController controller) {
        this.mVideoItem = item;
        mTitle.setText(item.videoTitle);
        mDes.setText(item.videoTitle);

        initClick(i);
        setIVideoController(controller);
        initEvent();

        //主镜头不显示border
        showBorder(i != 0);

        if(mVr != null) {
            mVr.setVisibility(View.VISIBLE);
        }
    }

    public void resetVr() {
        if(mVRLibrary == null)
            return;
        mVRLibrary.resetPinch();
        // reset touch
        if (mVRLibrary.getInteractiveMode() == MDVRLibrary.INTERACTIVE_MODE_TOUCH){
            mVRLibrary.resetTouch();
        }
    }

    protected MDVRLibrary createVRLibrary(GLTextureView view) {
        return MDVRLibrary.with((Activity) context)
                .displayMode(MDVRLibrary.DISPLAY_MODE_NORMAL)
                .interactiveMode(supportVRMotionMode() ? MDVRLibrary.INTERACTIVE_MODE_MOTION_WITH_TOUCH : MDVRLibrary.INTERACTIVE_MODE_TOUCH)
                .asVideo(new MDVRLibrary.IOnSurfaceReadyCallback() {
                    @Override
                    public void onSurfaceReady(Surface surface) {
                        Utils.Log(TAG, "VR..........onSurfaceReady");
                        updateSurface(surface);
                    }
                })
                .pinchEnabled(true)
                .build(view);
    }

    protected void updateSurface(Surface surface) {
        if(mSurfaceFilled.get())
            return;
        if(mHelper != null) {
            mHelper.updateSurface(surface);
            Utils.Log(TAG, "VR..........update vr surface");
            mSurfaceFilled.set(true);
        }
    }

    /**
     * 切换交互模式
     * @return
     */
    public int switchInteractiveMode() {
        if(mVRLibrary == null)
            return 0;
        int mode = 0;
        if(mVRLibrary.getInteractiveMode() == MDVRLibrary.INTERACTIVE_MODE_MOTION_WITH_TOUCH) {
            mGesture.setImageResource(R.drawable.icon_vr_motion);
            mode = MDVRLibrary.INTERACTIVE_MODE_TOUCH;

            GuideConstants.showVrGuide((Activity) getContext(), this, false, null);
        } else {
            mGesture.setImageResource(R.drawable.icon_vr_motionlock);
            mode = MDVRLibrary.INTERACTIVE_MODE_MOTION_WITH_TOUCH;
        }
        mVRLibrary.switchInteractiveMode((Activity) context, mode);
        return mode;
    }

    /**
     * 切换显示模式
     * @return
     */
    public int switchDisplayMode() {
        if(mVRLibrary == null)
            return 0;
        int mode = 0;
        if(mVRLibrary.getDisplayMode() == MDVRLibrary.DISPLAY_MODE_GLASS) {
            mGlass.setImageResource(R.drawable.icon_vr_glasson);
            mode = MDVRLibrary.DISPLAY_MODE_NORMAL;
        } else {
            mGlass.setImageResource(R.drawable.icon_vr_glassoff);
            mode = MDVRLibrary.DISPLAY_MODE_GLASS;

            //切换成全屏模式和MOTION模式
            if(mVRLibrary.getInteractiveMode() != MDVRLibrary.INTERACTIVE_MODE_MOTION_WITH_TOUCH)
                switchInteractiveMode();

            if(iController != null && iController.isMiddleMode())
                switchViewSize();

        }
        mVRLibrary.switchDisplayMode((Activity) context);

        return mode;
    }

    public AbstractVideoHelper getVideoHelper(VideoPlayModel video, String x, String y, AbsPlayCallback playCallback) {
        this.mVideo = video;
        prepareVrLibrary();
        mVRLibrary.updateAngleXY(getAngleXY(x, y));
        mHelper = new MajorVRTextureVideoHelper(context, video, new ISurfaceTextureProvider() {
            @Override
            public Surface getSurface() {
                if(mVRLibrary != null)
                    return mVRLibrary.getSurface();
                return null;
            }
        }, playCallback);
        return mHelper;
    }

    protected void prepareVrLibrary() {
        if(mVRLibrary == null)
            mVRLibrary = createVRLibrary(mVrView);
    }

    private float[] getAngleXY(String x, String y) {
        float[] result = new float[2];
        if(StringUtils.isNotBlank(x))
            result[0] = Float.parseFloat(x);
        else
            result[0] = 0;

        if(StringUtils.isNotBlank(y))
            result[1] = Float.parseFloat(y);
        else
            result[1] = 0;
        return result;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(mVRLibrary != null)
            return mVRLibrary.handleTouchEvent(event) || super.onTouchEvent(event);
        return super.onTouchEvent(event);
    }

    public void onDestroy() {
        super.onDestroy();
        if(mVRLibrary != null)
            mVRLibrary.onDestroy();
    }

    public void onResume() {
        if(mVRLibrary != null) {
            mVRLibrary.onResume(context);
        }
    }

    public void onPause() {
        if(mVRLibrary != null)
            mVRLibrary.onPause(context);
    }

    @Override
    public void removeMask() {
        mVideoBg.setVisibility(GONE);
    }

    public boolean consumeTouchEvent() {
        return true;
    }

}